#!/usr/bin/env python3
"""
Create a test image with XMP metadata.
Requires: pip install Pillow
"""

import os
import struct
from io import BytesIO

try:
    from PIL import Image
except ImportError:
    print("Please install Pillow: pip install Pillow")
    exit(1)

# Sample XMP data - must start with the XMP preamble
XMP_PREAMBLE = b'http://ns.adobe.com/xap/1.0/\x00'

XMP_CONTENT = b'''<?xpacket begin="\xef\xbb\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.1.0">
  <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <rdf:Description rdf:about=""
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:xmp="http://ns.adobe.com/xap/1.0/"
        xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/"
        xmlns:tiff="http://ns.adobe.com/tiff/1.0/"
        xmlns:exif="http://ns.adobe.com/exif/1.0/">
      <dc:title>
        <rdf:Alt>
          <rdf:li xml:lang="x-default">OpenHarmony XMP Test Image</rdf:li>
        </rdf:Alt>
      </dc:title>
      <dc:creator>
        <rdf:Seq>
          <rdf:li>OpenHarmony Developer</rdf:li>
        </rdf:Seq>
      </dc:creator>
      <dc:description>
        <rdf:Alt>
          <rdf:li xml:lang="x-default">This is a test image with XMP metadata for OpenHarmony metadata-extractor testing.</rdf:li>
        </rdf:Alt>
      </dc:description>
      <dc:subject>
        <rdf:Bag>
          <rdf:li>OpenHarmony</rdf:li>
          <rdf:li>XMP</rdf:li>
          <rdf:li>Metadata</rdf:li>
          <rdf:li>Test</rdf:li>
        </rdf:Bag>
      </dc:subject>
      <xmp:CreatorTool>OpenHarmony XMP Test Tool</xmp:CreatorTool>
      <xmp:CreateDate>2024-01-15T10:30:00+08:00</xmp:CreateDate>
      <xmp:ModifyDate>2024-01-15T12:00:00+08:00</xmp:ModifyDate>
      <xmp:Rating>5</xmp:Rating>
      <photoshop:City>Beijing</photoshop:City>
      <photoshop:State>Beijing</photoshop:State>
      <photoshop:Country>China</photoshop:Country>
      <photoshop:Credit>OpenHarmony Team</photoshop:Credit>
      <photoshop:AuthorsPosition>Developer</photoshop:AuthorsPosition>
      <tiff:Make>OpenHarmony</tiff:Make>
      <tiff:Model>Virtual Camera</tiff:Model>
      <tiff:ImageWidth>400</tiff:ImageWidth>
      <tiff:ImageLength>300</tiff:ImageLength>
      <exif:ColorSpace>1</exif:ColorSpace>
    </rdf:Description>
  </rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>'''

def create_xmp_jpeg(output_path: str, width: int = 400, height: int = 300):
    """Create a JPEG image with embedded XMP metadata."""
    
    # Create a simple gradient image
    img = Image.new('RGB', (width, height))
    pixels = img.load()
    
    for y in range(height):
        for x in range(width):
            # Create a nice gradient
            r = int(255 * x / width)
            g = int(255 * y / height)
            b = int(128 + 64 * ((x + y) % 2))
            pixels[x, y] = (r, g, b)
    
    # Add some text-like pattern
    for y in range(50, 100):
        for x in range(50, 350):
            if (x + y) % 10 < 3:
                pixels[x, y] = (255, 255, 255)
    
    # Save to bytes first
    img_bytes = BytesIO()
    img.save(img_bytes, format='JPEG', quality=95)
    jpeg_data = bytearray(img_bytes.getvalue())
    
    # Build XMP APP1 segment
    xmp_data = XMP_PREAMBLE + XMP_CONTENT
    
    # APP1 segment: FF E1 + 2-byte length (big endian) + data
    # Length includes the 2 length bytes but not the marker
    segment_length = len(xmp_data) + 2
    
    app1_segment = bytearray()
    app1_segment.append(0xFF)  # Marker prefix
    app1_segment.append(0xE1)  # APP1 marker
    app1_segment.extend(struct.pack('>H', segment_length))  # Length (big endian)
    app1_segment.extend(xmp_data)
    
    # Find where to insert (after SOI marker FFD8)
    # We need to insert before any existing APP segments
    insert_pos = 2  # After FFD8 (SOI)
    
    # Create output with XMP inserted
    output_data = bytearray()
    output_data.extend(jpeg_data[:2])  # FFD8 (SOI)
    output_data.extend(app1_segment)    # XMP APP1
    output_data.extend(jpeg_data[2:])   # Rest of JPEG
    
    # Write to file
    with open(output_path, 'wb') as f:
        f.write(output_data)
    
    print(f"Created: {output_path}")
    print(f"Image size: {width}x{height}")
    print(f"XMP preamble: {XMP_PREAMBLE[:30]}...")
    print(f"XMP data size: {len(xmp_data)} bytes")
    print(f"APP1 segment size: {len(app1_segment)} bytes")
    print(f"Total file size: {len(output_data)} bytes")
    
    # Verify the structure
    print("\n--- Verifying JPEG structure ---")
    print(f"Byte 0-1: {hex(output_data[0])} {hex(output_data[1])} (should be FF D8)")
    print(f"Byte 2-3: {hex(output_data[2])} {hex(output_data[3])} (should be FF E1)")
    print(f"APP1 length bytes: {hex(output_data[4])} {hex(output_data[5])}")
    preamble_start = output_data[6:6+30]
    print(f"XMP preamble start: {preamble_start}")

if __name__ == '__main__':
    # Get script directory
    script_dir = os.path.dirname(os.path.abspath(__file__))
    project_root = os.path.dirname(script_dir)
    
    # Output to entry's rawfile directory
    output_dir = os.path.join(project_root, 'entry', 'src', 'main', 'resources', 'rawfile')
    os.makedirs(output_dir, exist_ok=True)
    
    output_path = os.path.join(output_dir, 'xmp_test_image.jpg')
    create_xmp_jpeg(output_path)
    
    print(f"\n=== Image saved to: {output_path} ===")
    print("\nXMP Properties included:")
    print("  - dc:title = OpenHarmony XMP Test Image")
    print("  - dc:creator = OpenHarmony Developer")
    print("  - dc:description = This is a test image...")
    print("  - dc:subject = OpenHarmony, XMP, Metadata, Test")
    print("  - xmp:CreatorTool = OpenHarmony XMP Test Tool")
    print("  - xmp:CreateDate = 2024-01-15T10:30:00+08:00")
    print("  - xmp:Rating = 5")
    print("  - photoshop:City = Beijing")
    print("  - photoshop:Country = China")
    print("  - tiff:Make = OpenHarmony")
    print("  - tiff:Model = Virtual Camera")
